package com.songcan.basics.core.controller;


import cn.hutool.core.util.StrUtil;
import com.google.code.kaptcha.Producer;
import com.songcan.basics.core.service.CommonFileService;
import com.songcan.common.contans.ImageType;
import com.songcan.common.exception.ObjectNotException;
import lombok.AllArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.imageio.ImageIO;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.util.Objects;
import java.util.concurrent.TimeUnit;


@AllArgsConstructor
@RestController
@RequestMapping("tool/")
public class CommonController {

    private Producer producer;
    private RedisTemplate redisTemplate;
    private final CommonFileService commonFileService;


    @GetMapping("/file")
    public void getByImage(String id, ImageType imageType, HttpServletResponse response) throws IOException {
        commonFileService.get(id,imageType,response);
    }

    @GetMapping("/verilyCode")
    public void  VerilyCode(HttpServletRequest request,
                            HttpServletResponse response) throws ServletException, IOException {


        String random = request.getParameter("random");
        if(Objects.isNull(random)|| StrUtil.isEmpty(random)){
            throw new ObjectNotException("随机数不能为空");
        }
        String key = "rand:"+random;
        response.setHeader("Pragma", "No-cache");
        response.setHeader("Cache-Control", "no-cache");
        response.setDateHeader("Expires", 0);
        response.setContentType("image/jpeg");
        //生成验证码
        String sRand = producer.createText();
        //生成文字验证码
        String text = producer.createText();

        //个位数字相加
        String s1 = text.substring(0, 1);
        String s2 = text.substring(1, 2);
        int count = Integer.valueOf(s1).intValue() + Integer.valueOf(s2).intValue();

        //生成图片验证码
        BufferedImage image = producer.createImage(s1 + "+" + s2 + "=?");
        redisTemplate.opsForValue().set(key, String.valueOf(count), 1, TimeUnit.MINUTES);
        // 向输出流中输出图片
        ImageIO.write(image, "JPEG", response.getOutputStream());
    }


}
